﻿using System.Windows;
using System.Windows.Input;

namespace WhiteRepositoryExplorer.Helpers
{
    public static class FocusExtension
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }


        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }


        public static readonly DependencyProperty IsFocusedProperty = 
                        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension), new UIPropertyMetadata(null, OnIsFocusedPropertyChanged));


        private static void OnIsFocusedPropertyChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)d;

            if (e.OldValue == null)
            {
                uie.GotFocus += (sender, args) => ((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
                uie.LostFocus += (sender, args) => ((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
            }
          
            if ((bool)e.NewValue)
            {
                uie.Focus(); // Don't care about false values.
                Keyboard.Focus(uie);
            }
        }
    }
}
